package com.ddone.controller;

import com.ddone.bean.User;
import com.ddone.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author ddone
 * @date 2024/3/24-13:48
 */
@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public String login(User user, HttpServletRequest request,
                        BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            request.setAttribute("msg","账号和密码不能为空");
        }
        User loginUser = userService.login(user);
        if (loginUser!=null) {
            request.setAttribute("user",loginUser);
            return "index";
        }
        request.setAttribute("msg","用户不存在");
        return "login";
    }

    @PostMapping
    public String save(User user,BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            log.error("保存用户有违规参数~~~");
            bindingResult.getFieldErrors().forEach(System.out::println);
            return "userAdd";
        }
        userService.save(user);
        return "redirect:/user";
    }

    @GetMapping
    public String list(Model model){
        List<User> userList = userService.list();
        model.addAttribute("userList", userList);
        return "userList";
    }

    @DeleteMapping("/{uId}")
    public String delete(@PathVariable String uId){
        userService.delete(uId);
        return "redirect:/user";
    }

    @GetMapping("/{uId}")
    public String getById(@PathVariable String uId,Model model){
        User user = userService.getById(uId);
        model.addAttribute("user",user);
        return "userUpdate";
    }
    @GetMapping("/detail/{uId}")
    public String detail(@PathVariable String uId,Model model){
        User user = userService.getById(uId);
        model.addAttribute("user",user);
        return "userView";
    }

    @PutMapping
    public String update(User user){
        userService.update(user);
        return "redirect:/user";
    }

    @PostMapping("/key")
    public String search(String keyword,Model model){
        List<User> userList = userService.search(keyword);
        model.addAttribute("userList", userList);
        return "userList";
    }
}
